package com.example.demo;

import org.eclipse.jgit.api.CloneCommand;
import org.eclipse.jgit.api.Git;
import org.eclipse.jgit.api.errors.GitAPIException;
import org.eclipse.jgit.lib.Repository;
import org.eclipse.jgit.storage.file.FileRepositoryBuilder;
import org.eclipse.jgit.transport.UsernamePasswordCredentialsProvider;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.File;
import java.io.IOException;



@Controller
public class JgitController {
    String giturl="https://github.com/shoukaiseki/ServerCenterOne.git";


    String targetPath ="/tmp/win/gittemp";

    String branch="master";


    @RequestMapping("/asus")
    @ResponseBody
    public String testgit() throws IOException {
        System.setProperty("http.sslVerify","false");
        System.setProperty("https.protocols","TLSv1.2,SSLv3");
        cloneRepository2(giturl,branch,targetPath);

        String javaversion=System.getProperty("java.version");

        return "url="+giturl+",branch="+branch+",targetPath="+targetPath
                +",javaversion="+javaversion;
    }


    private  void cloneRepository2(String url, String branch, String targetPath) throws IOException {

        File path =new File(targetPath);
        if(path.exists()){
            path.delete();
        }
        path.mkdirs();
        Git result = null;
        FileRepositoryBuilder builder = new FileRepositoryBuilder();
        Repository repository = builder.setGitDir(path).readEnvironment().findGitDir().build();

        Git git = new Git(repository);
        CloneCommand clone = git.cloneRepository();
        clone.setDirectory(path).setURI(url);
        try {
           // UsernamePasswordCredentialsProvider user=new UsernamePasswordCredentialsProvider("jiang28555@gmail.com","password");
            //clone.setCredentialsProvider(user);
            clone.call();
        } catch (GitAPIException e) {
            e.printStackTrace();
        }
    }
}
